"""
项目应用初始化文件--应用程序实例、数据库实例、注册蓝图、日志、CSRF等
"""
import logging
from logging.handlers import RotatingFileHandler
#  flask封装的session对象
from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
# flask_session用来指定session信息的存储位置
from flask_session import Session
from config import config,Config
# 第二天，登录界面的实现
from redis import StrictRedis
from flask_wtf import CSRFProtect, csrf
# 实例化sqlalchemy对象
db = SQLAlchemy()
# 实例化resis数据库对象，存储业务逻辑相关数据，如图片验证码等,redis二进制转换成字符串
redis_store = StrictRedis(host= Config.REDIS_HOST, port= Config.REDIS_PORT, decode_responses=True)



logging.basicConfig(level=logging.DEBUG)
file_log_hander = RotatingFileHandler('python_practice/News_information/logs/log', maxBytes=1024*1024*10 ,backupCount=10)
formatter = logging.Formatter('%(levelname)s %(filename)s %(lineno)s %(message)s')
file_log_hander.setFormatter(formatter)
logging.getLogger().addHandler(file_log_hander)

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # 实例化session对象
    Session(app)
    db.init_app(app)
    CSRFProtect(app)
    # 每次请求后，写入客户端的cookie中，写入csrf_token
    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response
    #  蓝图第3步，注册蓝图对象，绑定app
    from info.modules.news import news_blue
    from info.modules.admin import admin_blue
    from info.modules.passport import passport_blue
    app.register_blueprint(news_blue)
    app.register_blueprint(admin_blue)
    app.register_blueprint(passport_blue)
    return app

